<!-- ==============放仔名单=============== -->
<template>
	<view class="container">
		<!-- 判断是否管理员 样式变化 -->
		<view v-if="isAdmin" class="tab-container">
			<scroll-view class="tab-scroll" scroll-x="true" :scroll-left="scrollLeft" :show-scrollbar="false">
				<view class="tab-content">
					<span 
						v-for="(item,index) in list_site" 
						:key="index" 
						@click="choose(item.id)"
						:class="item.id === bg_index ? 'choose_bg' : 'bg'"
						class="tab-item"
					>{{item.text}}</span>
				</view>
			</scroll-view>
		</view>
		<view v-else class="tab">
			<span class="normalBg" style="width: 50%;">{{bg_index}}仓</span>
		</view>
		<view class="nav">
			<!-- 日期选择 -->
			<view class="date">
				<view class="date_item_date row-around" style="background-color: #9EB8E3;
				color: #fff; height: 52rpx; border-radius: 10rpx;" @click.stop="handleDate">
					<span>{{year}}年</span>
					<span>{{month}}月</span>
					<span>{{day}}日</span>
					<uni-icons type="down" size="28" color="#fff"
						:style="{transform: `rotate(${rotatedate}deg)`}"></uni-icons>
				</view>
				<transition name="sort">
					<scroll-view class="date_item_list_date" v-show="showdate" scroll-y="true" style="height: 500rpx; overflow: hidden;">
						<view class="date_item row-around" v-for="(i,k) in previousMonths" :key="k"
							:class="{'choosed': i.year === year && i.month === month && i.day == day}"
							style="background-color: #E8F2FC" @click.stop="selectDate(i)">
							<span>{{i.year}}年</span>
							<span>{{i.month}}月</span>
							<span>{{i.day}}日</span>
						</view>
					</scroll-view>
				</transition>
			</view>
			<!-- 操作选择 -->
			<view class="date">
				<view class="date_item_op row-around"
					style="background-color: #9EB8E3; color: #fff; height: 52rpx;border-radius: 10rpx;"
					@click.stop="handleOp">
					<span>{{operation_show}}</span>
					<uni-icons type="down" size="28" color="#fff"
						:style="{transform: `rotate(${rotateop}deg)`}"></uni-icons>
				</view>
				<transition name="sort">
					<view class="date_item_list_op" v-show="showop">
						<view class="date_item row-center" v-for="(i,k) in oplist" :key="k"
							:class="{choosed: i.name === operation_show}" style="background-color: #E8F2FC"
							@click.stop="selectOp(i)">
							<span>{{i.name}}</span>
						</view>
					</view>
				</transition>
			</view>
			<!-- 快捷键 -->
			<view class="speed_put_container">
				<button @click="speed_put" :class="{complete: isAllSelect}"
					:disabled="!putList.length">{{isAllSelect ? '完成' : '快捷放仔'}}</button>
			</view>
		</view>		
		
		<view class="content" style="height: 74vh;">
			<u-loading class="loading" mode="circle" v-if="isLoading" size="36" color="blue"></u-loading>
			<template v-else>
				<view v-if="isnoList" class="noList">暂无数据</view>
				
				<scroll-view v-else class="scroll_container" scroll-y="true" style="height: 70vh">
					<view class="putList_item row-around mt10" v-for="(item,index) in putList" :key="index">
						<view class="left row-around">
							<uni-icons type="fire-filled" color="blue" size="24"></uni-icons>
							<span
								style="font-size: 22.02rpx;">{{format_houseId(item.house_id,bg_index)+'-'+item.cage_id}}</span>
						</view>
						<view class="middle">
							<span style="font-size: 22.02rpx;">放仔数量</span>
							<view :style="styleVar" class="peigon_select">
								<view class="select_top" @click="showSelect(index)"
									:class="{selectTop_choose_bg: item.isSelected}">
									<view class="selectinfo">{{ item.put_number }}</view>
									<uni-icons type="down" size="28" :class="{rotate: item.isSelected}"
										class="icons"></uni-icons>
								</view>
								<view class="select_dorp" :class="{show: item.isSelected,}">
									<li class="select_item" v-for="(num, index_putNum) in select_list"
										:key="index_putNum" @click="handler(num,index)">{{ num }}
									</li>
								</view>
							</view>
						</view>
						<view v-if="!isAllSelect" @click="PUT_ONE(item)" class="put row-around">放仔</view>
						<view class="icon_selectfail row-around" v-if="!item.choosed && isAllSelect"
							@click="put_choose(item)">
						</view>
						<view class="icon_selectsuccess row-around" v-if="item.choosed && isAllSelect"
							@click="put_choose(item)">
						</view>
					</view>
				</scroll-view>
				
			</template>
			<view v-show="isAllSelect" class="operation_container row-around">
				<view class="left">
					<button class="row-around" @click="selectAll" v-if="!allSelect">全选</button>
					<button class="row-around" @click="deselectAll" v-else>取消全选</button>
				</view>
				<view class="right">
					<button :disabled="!paramsList.length" class="row-around" @click="PUT_ALL">放仔</button>
				</view>
			</view>
		</view>
		<view class="pagination">
			<Pagination @getPageNo="getPageNo" :pageNo="pageNo" :pageSize="pageSize" :total="total" :continues="3"></Pagination>
		</view>
		<!-- 顶部提示 -->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import { mapGetters } from 'vuex'
	import {
		reqPutEggs,
		reqGetPUTlist,
		reqHistoryList,
	} from '@/api/index.js'
	import {
		format
	} from '@/utils/format_HouseId.js'
	import {
		getNowDate
	} from '@/getTime.js'
	import Pagination from '@/components/pagination/pagination.vue'
	import Cookie from '@/utils/cookie.js'
	
	export default {
		props: {
			select_list: {
				type: Array,
				default: function() {
					return [1, 2, 3, 4];
				}
			},
			width: {
				type: String,
				default: "80rpx"
			},
			height: {
				type: String,
				default: "40rpx"
			},
			listLength: {
				type: Number,
				default: 4
			}
		},
		components:{
			Pagination
		},
		data() {
			return {
				// 操作列表
				oplist: [{
					name: '全部待放',
					operation: 'whipAddStay'
				},{
					name: '抽蛋待放',
					operation: 'whipping'
				}, {
					name: '留窝待放',
					operation: 'stay'
				}],
				list_site: [], // 动态生成的仓库列表
				bg_index: null, // 当前选中的仓库ID
				// 放仔名单
				paramsList: [],
				putList: [],
				selectInfo: 1,
				select_show: false,
				isAllSelect: false, // 判断是否为快捷放仔状态

				// 初始选中的日期
				year: new Date().getFullYear(),
				month: new Date().getMonth() + 1,
				day: new Date().getDate(),
				// 初始选中的操作
				operation_show: '全部待放',
				operation: 'whipAddStay',
				// 接口请求用的仓库ID（与当前选中同步）
				opSite: null,
				// 下拉框
				rotatedate: 0,
				rotateop: 0,
				showdate: false,
				showop: false,
				// 分页器
				pageNo: 1,
				pageSize: 20,
				total: 0,
				
				// 下拉框
				selectInfo: this.select_list[3],
				select_show: false,

				isLoading: false,
				isnoList: false,
				scrollLeft: 0
			}
		},
		computed: {
			// 使用 Vuex 中的 allSites getter
			...mapGetters(['isNet', 'whipCount', 'stayCount', 'token', 'operationSiteId', 'allSites']),
			// 判断是否为管理员
			isAdmin() {
				return Cookie.get('ROLE') === 'admin'
			},
			previousMonths() {
				return this.getPreviousMonths()
			},
			styleVar() {
				return {
					'--select_width': this.width,
					'--select_height': this.height,
					'--select_drop_height': this.height * this.listLength + 'rpx'
				}
			},
			// 判断显示全选 or 取消全选
			allSelect() {
				return this.paramsList.length === this.putList.length
			}
		},
		watch: {
			bg_index(newValue, oldValue) {
				if (newValue !== oldValue) {
					this.opSite = newValue // 同步接口请求用的仓库ID
					this.getPUTlist()
					this.reset()
					this.scrollToSelected()
				}
			},
			// 监听仓库列表变化，重新生成仓库选项
			allSites: {
				handler(newVal) {
					console.log('仓库列表变化:', newVal);
					this.generateSiteList();
				},
				deep: true
			},
			// 监听当前操作站点变化
			operationSiteId(newVal) {
				console.log('操作站点变化:', newVal);
				this.generateSiteList();
			}
		},
		created() {
			// 生成仓库列表
			this.generateSiteList();
		},
		mounted() {
			// 初始化数据
			if (this.list_site.length > 0) {
				this.getPUTlist()
			}
		},
		onShow() {
			// 确保页面显示时刷新数据
			this.generateSiteList();
		},
		methods: {
			// 动态生成仓库列表 - 采用与 operation.vue 相同的方式
			generateSiteList() {
				console.log('生成仓库列表 - 开始');
				console.log('当前用户角色:', Cookie.get('ROLE'));
				console.log('allSites:', this.allSites);
				console.log('operationSiteId:', this.operationSiteId);
				
				this.list_site = [];
				
				if (this.isAdmin && this.allSites && this.allSites.length > 0) {
					console.log('管理员模式，显示所有仓库');
					
					// 管理员显示所有仓库
					this.allSites.forEach(site => {
						this.list_site.push({
							id: site,
							text: `${site}仓`,
							handle: site === this.operationSiteId
						});
					});
					
					// 设置默认选中的仓库ID
					this.bg_index = this.operationSiteId;
				} 
				else if (!this.isAdmin && this.operationSiteId !== undefined && this.operationSiteId !== null) {
					console.log('普通员工模式，显示当前仓库');
					
					// 普通员工只显示自己的仓库
					this.list_site.push({
						id: this.operationSiteId,
						text: `${this.operationSiteId}仓`,
						handle: true
					});
					this.bg_index = this.operationSiteId;
				}
				// 如果数据有问题，显示默认值
				else {
					console.log('使用默认值');
					this.list_site.push({
						id: 1,
						text: '1仓',
						handle: true
					});
					this.bg_index = 1;
				}
				
				// 同步接口请求用的仓库ID
				this.opSite = this.bg_index;
				
				console.log('生成的仓库列表:', this.list_site);
				console.log('当前选中的site_id:', this.bg_index);
				
				// 滚动到选中的仓库
				this.$nextTick(() => {
					this.scrollToSelected();
				});
			},
			// 滚动到选中的仓库
			scrollToSelected() {
				const selectedIndex = this.list_site.findIndex(item => item.id === this.bg_index);
				if (selectedIndex !== -1) {
					// 计算滚动位置，使选中的仓库居中显示
					this.scrollLeft = (selectedIndex - 1) * 150; // 150是每个仓库项的预估宽度
				}
			},
			// 点击日期框
			handleDate() {
				this.showdate = !this.showdate
				this.rotatedate = this.showdate ? 180 : 0
			},
			// 点击操作框时
			handleOp() {
				this.showop = !this.showop
				this.rotateop = this.showop ? 180 : 0
			},
			// 选择日期时
			selectDate(i) {
				this.handleDate()
				this.pageNo = 1 // 重置页码
				this.year = i.year
				this.month = i.month
				this.day = i.day
				this.getPUTlist()
			},
			// 选择操作时
			selectOp(i) {
				this.handleOp()
				this.pageNo = 1 // 重置页码
				this.operation_show = i.name
				this.operation = i.operation
				this.getPUTlist()
			},
			
			// 发送抽蛋留窝历史操作
			getHistoryList() {
				this.isLoading = true
				const params = {
					year: this.year,
					month: this.month,
					day: this.day,
					operation: this.operation,
					siteId: this.opSite,
					page: this.pageNo,
					pageSize: this.pageSize
				}
				reqHistoryList(params).then(resp => {
					if (resp.code === 200) {
						this.list = resp.data
						this.total = resp.total || 0
						this.isnoList = !(resp.data && resp.data.length > 0)
					}
				}).finally(() => {
					this.isLoading = false
					uni.stopPullDownRefresh()
				})
			},
			// 给出距今前2个月对应的年份和月份和日期
			getPreviousMonths() {
				const currentDate = new Date()
				const days = []
				let flag = true
				for (let i = 0; i < 3; i++) {
					const previousMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1)
					const year = previousMonth.getFullYear()
					const month = previousMonth.getMonth() + 1
					const totalDays = this.getTotalDaysInMonth(year, previousMonth.getMonth())
					
					if (flag) {
						// 当前月从今天开始往前推
						for (let day = currentDate.getDate(); day >= 1; day--) {
							days.push({ year, month, day })
						}
						flag = false
					} else {
						// 前几个月显示所有天数
						for (let day = totalDays; day >= 1; day--) {
							days.push({ year, month, day })
						}
					}
				}
				return days
			},
			// 算出具体某个月的天数
			getTotalDaysInMonth(year, month) {
			    const nextMonth = new Date(year, month + 1, 1)
			    const currentMonth = new Date(year, month, 1)
			    const diffTime = nextMonth.getTime() - currentMonth.getTime()
			    return Math.round(diffTime / (1000 * 60 * 60 * 24))
			},
			// 获取页号
			getPageNo(num){
				this.pageNo = num
				this.getPUTlist()
			},
			// 格式化鸽笼号
			format_houseId(houseId, siteId) {
				return format(houseId, siteId)
			},
			// 获取放仔名单
			async getPUTlist() {
				if (!this.opSite) {
					console.log('仓库ID不存在，跳过请求');
					return // 仓库ID不存在时不请求
				}
				
				this.isLoading = true
				this.isnoList = false
				
				try {
					const resp = await reqGetPUTlist({
						siteId: this.opSite,
						page: this.pageNo,
						pageSize: this.pageSize,
						day: this.day,
						month: this.month,
						year: this.year,
						operation: this.operation
					})
					
					if (resp.code === 200) {
						this.putList = resp.data || []
						this.total = resp.totalCount || 0
						this.isnoList = this.putList.length === 0
					}
				} catch (error) {
					console.error('获取放仔名单失败', error)
					this.isnoList = true
				} finally {
					this.isLoading = false
				}
			},
			// 切换仓库
			choose(siteId) {
				this.bg_index = siteId
				// 更新选中状态
				this.list_site.forEach(item => {
					item.handle = item.id === siteId
				})
				// 滚动到选中的位置
				this.$nextTick(() => {
					this.scrollToSelected();
				});
			},
			// 进入或退出快捷放仔状态
			speed_put() {
				this.isAllSelect = !this.isAllSelect
				this.deselectAll()
			},
			// 在切换仓号时将快捷放仔状态置为初始状态
			reset() {
				this.isAllSelect = false
				this.deselectAll()
			},
			// 全选
			selectAll() {
				this.putList.forEach(item => {
					item.choosed = true
					item.site_id = this.opSite
					if (!this.paramsList.includes(item)) {
						this.paramsList.push(item)
					}
				})
			},
			// 取消全选
			deselectAll() {
				this.putList.forEach(item => {
					const index = this.paramsList.indexOf(item)
					if (index > -1) {
						this.paramsList.splice(index, 1)
						item.choosed = false
					}
				})
			},
			
			// 选择/取消选择单个项
			put_choose(item) {
				item.choosed = !item.choosed
				const index = this.paramsList.indexOf(item)
				
				if (index > -1) {
					this.paramsList.splice(index, 1)
				} else {
					item.site_id = this.opSite
					this.paramsList.push(item)
				}
			},
			// 发送多个放仔数据
			PUT_ALL() {
				this.concurPUT(this.paramsList, 10).then(resp => {
					const successResp = resp.find(r => r.code === 200)
					if (successResp) {
						this.getPUTlist()
						this.speed_put()
						this.$refs.uToast.show({
							title: successResp.msg,
							type: successResp.type,
							duration: 800,
							position: 'top'
						})
					} else {
						this.$refs.uToast.show({
							title: '操作失败，请重试',
							type: 'error',
							duration: 800,
							position: 'top'
						})
					}
				})
			},
			// 单个鸽笼放仔
			async PUT_ONE(data) {
				const params = {
					siteId: this.opSite,
					houseId: data.nfc_id,
					cageId: data.cage_id,
					cageStatu: '带仔中',
					putNumber: data.put_number,
					putTime: getNowDate()
				}
				
				try {
					const result = await reqPutEggs(params)
					if (result.code === 200) {
						this.getPUTlist()
					}
					this.$refs.uToast.show({
						title: result.msg,
						type: result.type,
						duration: 800,
						position: 'top'
					})
				} catch (error) {
					this.$refs.uToast.show({
						title: '操作失败',
						type: 'error',
						duration: 800,
						position: 'top'
					})
				}
			},

			// 放仔函数
			PUT(data) {
				const params = {
					siteId: this.opSite,
					houseId: data.nfc_id,
					cageId: data.cage_id,
					cageStatu: '带仔中',
					putNumber: data.put_number,
					putTime: getNowDate()
				}
				
				return new Promise((resolve, reject) => {
					reqPutEggs(params).then(resp => {
						resolve(resp)
					}).catch(err => {
						reject(err.response?.data || { code: 500, msg: '请求失败' })
					})
				})
			},

			// 并发请求
			concurPUT(paramsList, maxNum) {
				return new Promise(resolve => {
					if (paramsList.length === 0) {
						resolve([])
						return
					}
					
					const result = []
					let index = 0
					let count = 0

					const request = () => {
						if (index >= paramsList.length) return
						
						const i = index
						const params = paramsList[i]
						index++
						
						this.PUT(params).then(resp => {
							result[i] = resp
						}).catch(err => {
							result[i] = err
						}).finally(() => {
							count++
							if (count === paramsList.length) {
								resolve(result)
							} else {
								request()
							}
						})
					}

					// 启动最大并发数的请求
					const num = Math.min(maxNum, paramsList.length)
					for (let i = 0; i < num; i++) {
						request()
					}
				})
			},
			// 显示下拉框
			showSelect(index) {
				this.putList.forEach((item, i) => {
					if (i !== index) item.isSelected = false
				})
				this.putList[index].isSelected = !this.putList[index].isSelected
			},
			// 选择放仔数量
			handler(num, index) {
				this.putList[index].put_number = num
				this.showSelect(index)
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff;
		position: relative;
	}

	.selectTop_choose_bg {
		box-shadow: 0px 0px 6px #709DF7;
	}

	.normalBg {
		display: block;
		background-color: #9EB8E3;
		width: 100%;
		color: #ffffff;
	}
	.bg {
		background-color: #E8F2FC;
	}
	

	.choose_bg {
		background-color: #9EB8E3;
	}

	.rotate {
		transform: rotate(180deg);
	}

	.icons {
		transition: all 0.3s;
	}
	
	.choosed {
		color: orangered
	}
	%date_item_list {
		width: 100%;
		font-weight: bold;
		position: absolute;
		transition: all linear 0.2s;
		z-index: 9999;
		font-size: 22.02rpx
	}
	.row-around {
	    display: flex;
	    justify-content: space-around;
	}
	.nav {
		display: flex;
		justify-content: space-around;
	
		.date {
			position: relative;
	
			border-radius: 5px;
	
			.date_item {
				height: 55.05rpx;
			}
	
			.date_item_date {
				width: 100%;
				height: 52rpx;
				font-weight: bold;
				padding: 1.83rpx 3.67rpx;
				font-size: 20.18rpx
			}
	
			.date_item_op {
				width: 100%;
				height: 52rpx;
				font-weight: bold;
				padding: 1.83rpx 16.51rpx;
				font-size: 20.18rpx
			}
	
			.date_item_cage {
				width: 100%;
				height: 52rpx;
				font-weight: bold;
				padding: 1.83rpx 16.51rpx;
				font-size: 20.18rpx
			}
	
			.date_item_list_date {
				@extend %date_item_list;
				height: 286.24rpx;
			}
	
			.date_item_list_op {
				@extend %date_item_list;
				height: 262.39rpx;
			}
	
			.date_item_list_cage {
				@extend %date_item_list;
				height: 143.12rpx;
			}
		}
	}

	.tab-container {
		position: sticky;
		top: 0;
		height: 8vh;
		background-color: #fff;
		z-index: 10;
	}

	.tab-scroll {
		width: 100%;
		height: 100%;
		white-space: nowrap;
	}

	.tab-content {
		display: inline-flex;
		align-items: center;
		height: 100%;
		padding: 0 20rpx;

		.tab-item {
			flex-shrink: 0;
			width: 132rpx;
			height: 54rpx;
			margin: 0 10rpx;
			text-align: center;
			line-height: 54rpx;
			border-radius: 10rpx;
			font-weight: bold;
			font-size: 32rpx;
		}
	}
	

	.container {
		.tab {
			display: flex;
			position: sticky;
			top: 0;
			justify-content: space-evenly;
			align-items: center;
			height: 8vh;
			background-color: #fff;

			span {
				width: 132rpx;
				height: 54rpx;
				text-align: center;
				line-height: 54rpx;
				border-radius: 10rpx;
				font-weight: bold;
				font-size: 32rpx
			}
		}

		.speed_put_container {
			position: relative;
			width: 27%;
			height: 55.05rpx;
			margin-bottom: 4.59rpx;
			button {
				width: 91.74rpx;
				height: 100%;
				position: absolute;
				right: 55.05rpx;
				color: #909399;
				font-size: 20.18rpx;
				line-height: 55.05rpx;
				&[disabled]{
					border: none;
				}
				&.complete {
					background-color: #19be6b;
					color: #fff;
					font-weight: bold;
				}
			}
		}
		
		

		.content {
			position: relative;
			width: 100%;
			height: 70vh;

			.loading,
			.noList {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
			}

			.scroll_container {

				.putList_item {
					width: 100%;
					height: 60rpx;

					span {
						font-weight: bold;
					}

					.left {
						width: 28%;
						height: 100%;
					}

					.middle {
						width: 36%;
						height: 100%;
						display: flex;
						justify-content: center;
						align-items: center;

						.peigon_select {
							display: flex;
							position: relative;
							flex-direction: column;
							justify-content: space-around;
							width: 80rpx !important;
							font-size: 22.02rpx;
							margin-left: 10rpx;

							.select_top {
								display: flex;
								justify-content: space-around;
								width: 80rpx;
								height: 40rpx;
								line-height: 40rpx;
								border: 1px solid #E6E6E6;
								border-radius: 5px;

								span {
									transition: all 0.5s;
								}

								.selectinfo {
									width: 80rpx;
									height: 40rpx;
									text-align: center;
									line-height: 40rpx;
								}
							}

							.select_dorp {
								display: none;
								position: absolute;
								top: 45rpx;
								width: 80rpx;
								max-height: 0px;
								transition: max-height 0.5s ease-in-out;
								border-radius: 10px;
								box-shadow: 0px 0px 6px #709DF7;
								z-index: 999;
								background-color: #fff;

								&.show {
									display: block;
									max-height: var(--select_drop_height);
								}

								.select_item {
									width: 80rpx;
									height: 25%;
									text-align: center;
									line-height: 40rpx;
									list-style: none;
								}
							}
						}
					}

					.put {
						width: 12%;
						height: 70%;
						font-weight: bold;
						font-size: 20.18rpx;
						border: 1px solid #fff;
						background-color: #2979ff;
						color: #fff;
						border-radius: 10px;
					}

					.icon_selectfail {
						width: 12%;
						height: 70%;
						background: url(../../static/images/icon_selectfail.png) no-repeat;
						background-size: 33% auto;
						background-position: 50% 50%;
					}

					.icon_selectsuccess {
						width: 12%;
						height: 70%;
						background: url(../../static/images/icon_selectsuccess.png) no-repeat;
						background-size: 33% auto;
						background-position: 50% 50%;
					}
				}
			}

			.operation_container {
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 55.05rpx;
				background-color: #f3f4f6;

				.left,
				.right {
					width: 50%;

					button {
						width: 100%;
						height: 40rpx;
						font-size: 22.02rpx;
					}
				}

				.left {
					border-right: 1px solid gray
				}
			}
		}
		.pagination{
			margin-top: 9.17rpx;
		}
	}
</style>